package org.openfans.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.openfans.domain.Facade;
import org.openfans.domain.Fans;
import org.openfans.domain.PreFans;
import org.openfans.util.ThreadFans;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class UserSessionFilter implements Filter {
	FilterConfig filterConfig = null;

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpSession se = ((HttpServletRequest) request).getSession();

		autoLogin(request, se);

		setThreadFans(se);

		chain.doFilter(request, response);
	}

	private void autoLogin(ServletRequest request, HttpSession se) {
		if (se.getAttribute("loginFans") == null) {
			Cookie[] cookies = ((HttpServletRequest) request).getCookies();
			for (int i = 0; cookies != null && i < cookies.length; i++) {
				if ("login".equals(cookies[i].getName())) {
					Fans f = getFacade()
							.authenticateFans(cookies[i].getValue());
					se.setAttribute("loginFans", f);
					break;
				}
			}
		}
	}

	private void setThreadFans(HttpSession se) {
		Fans f = (Fans) se.getAttribute("loginFans");
		if (f == null) {
			f = new PreFans();
			se.setAttribute("loginFans", f);
		}
		ThreadFans.set(f);
	}

	public void destroy() {
	}

	private Facade getFacade() {
		return (Facade) WebApplicationContextUtils.getWebApplicationContext(
				filterConfig.getServletContext()).getBean("facade");
	}
}
